//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"

TForm1 *Form1;

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
	SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) | WS_EX_LAYERED);
}

void __fastcall TForm1::WndProc(TMessage &Msg)
{
	BOOL handled = false;
	LRESULT lr = SciterProcND(this->Handle, Msg.Msg, Msg.WParam, Msg.LParam, &handled);

	switch(Msg.Msg)
	{
		case WM_CREATE:
		{
			SciterLoadFile(this->Handle, L"../GUI/UI.html");
			break;
		}
	}

	TForm::WndProc(Msg);
}

//---------------------------------------------------------------------------
void __fastcall TForm1::FormShow(TObject *Sender)
{
	dom::element root = dom::element::root_element(this->Handle);

	unsigned x = root.children_count();

	CEventHandler *EventHandler = new CEventHandler(this->Handle);

	// change caption of button
	dom::element button = root.find_first("button");
	button = button.last_sibling();           
	button.attach_event_handler(EventHandler);

	dom::element closeButton = root.find_first("[id=\"close\"]");
	closeButton.attach_event_handler(EventHandler);

	dom::element minimizeButton = root.find_first("[id=\"minimize\"]");
	minimizeButton.attach_event_handler(EventHandler);

//	button.set_text(L"Native event handler");
	/*
	// add new button
	dom::element p = dom::element::create("button", L"new button");
	p.attach_event_handler(EventHandler);
	root.append(p);*/
}
//---------------------------------------------------------------------------


CEventHandler::CEventHandler(HWND Handle)
{
	m_hWnd = Handle;
}

bool CEventHandler::handle_event(HELEMENT he, BEHAVIOR_EVENT_PARAMS &params)
{
	dom::element el = he;

	switch(params.cmd)
	{
		case BUTTON_CLICK:
		{
			const wchar_t *id = el.get_attribute("id");
			AnsiString str(id);

			if(str == "close")
			{
				SendMessage(m_hWnd, WM_CLOSE ,0, 0);
				break;
			}

			if(str == "minimize")
			{
				SendMessage(m_hWnd, WM_COMMAND ,419, 0);
				break;
			}

			Application->MessageBox("Native message", Application->Title.c_str(), MB_OK | MB_ICONINFORMATION);
			break;
		}
	}

	return false;
}

bool CEventHandler::handle_mouse(HELEMENT he, MOUSE_PARAMS& params )
{
    switch(params.cmd)
	{   /*
		case MOUSE_ENTER:
		{
			dom::element button = he;
			button.set_text(L"mouse enter");
			break;
		}

		case MOUSE_LEAVE:
		{
			dom::element button = he;
			button.set_text(L"mouse leave");
			break;
		} */
	}

	return false;
}
